'use strict';
var login_user = login_user || {}
var timeout_list = timeout_list || {}
/**
 * 用户登录成功,查询是否已登录
 */

/**
 * model
 * @type {Class}
 */
module.exports = class extends think.Model {
  adduser (user, type, key) {
    if (!(user && type && key)) {
      console.log('传入参数不正确')
      return
    }
    if ( user.id in login_user ) { //用户存在
      if ( type in login_user[user.id]) { // 登录方式存在
        if (login_user[user.id][type].socket) {
          login_user[user.id][type].socket.emit('remote_logon', user)
        }
        console.log('重复登录');
      }
    }
    login_user[user.id] = login_user[user.id] || {}
    login_user[user.id].user_info = user
    login_user[user.id][type] = login_user[user.id][type] || {}
    login_user[user.id][type].user_info = user
    login_user[user.id][type].key = key
  }
  getuser (opt, ws) {
    if (!opt) {
      return {
        state: 2,
        data: login_user
      }
    }
    if (login_user[opt.id]) {
      if (login_user[opt.id][opt.type]) {
        if (ws) {
          login_user[opt.id][opt.type].socket = ws
        }
        return {
          state: 1,
          data: login_user[opt.id][opt.type]
        }
      }
    }
    return {
      state: -1,
      errmsg: 'The specified user does not exist.'
    }
  }
  isLogin (data) {
    try {
      if (!(data.user_id in login_user)) { // 用户不存在
        this.adduser(data.info, data.type, data.key)
      }
      if (!(data.type in login_user[data.user_id])) { // 用户不存在
        this.adduser(data.info, data.type, data.key)
      }
    } catch (e) {
      return { status: -1, msg: '用户已在其他地方登录，请重新登录' }
    }
    if (login_user[data.user_id][data.type].key && login_user[data.user_id][data.type].key == data.key) { 
      return { status: 1, msg: '当前设备登录正常' }
    } else {
      return { status: -1, msg: '用户已在其他地方登录，请重新登录' }
    }
  }
  setUser (opt) {
    console.log('设置socket')
    console.log(opt)
    if(!opt) return 
    if (login_user[opt.id]) {
      if (login_user[opt.id][opt.type]) {
        login_user[opt.id][opt.type] = opt.data
      }
    }
  }
  getTimeoutList () {
    return timeout_list
  }
  clearTimeoutList (openid) {
    console.log('清除超时离线回复', openid)
    if (openid in timeout_list) {
      clearTimeout(timeout_list[openid])
    }
  }
}